package com.cgc.venus.server.core.es;

import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Created by Administrator on 16-7-29.
 */
@Component
public class BaseElasticsearch {
    @Autowired
    private ElasticsearchDataSource esDataSource;
    public ElasticsearchDataSource getEsDataSource() {
        return esDataSource;
    }
    public void setEsDataSource(ElasticsearchDataSource esDataSource) {
        this.esDataSource = esDataSource;
    }

    /**
     * 系统自动产生id 创建1个文档
     * @param index 索引名称
     * @param type  索引type
     * @param sourcecontent 要索引的内容
     */
    public boolean createIndex(String index,String type,String sourcecontent) throws Exception {
        Client client=null;
        try{
            client=esDataSource.getClient();
            IndexResponse response = client.prepareIndex(index, type).setSource(sourcecontent).execute().actionGet();
            return response.isCreated();
        }finally {
            if(client!=null){
                esDataSource.releaseClient(client);
            }
        }
    }

    /**
     * 自己设置id创建1个文档
     * @param index 索引名称
     * @param type  索引type
     * @param sourcecontent 要索引的内容
     * @param id
     */
    public boolean createIndexById(String index, String type, String sourcecontent, String id) throws Exception {
        Client client=null;
        try{
            client=esDataSource.getClient();
            IndexResponse response = client.prepareIndex(index, type).setId(id).setSource(sourcecontent).execute().actionGet();
            return response.isCreated();
        }finally {
            if(client!=null){
                esDataSource.releaseClient(client);
            }
        }
    }

    /**
     * 系统自动产生id 批量创建个文档
     * @param index 索引名称
     * @param type  索引type
     * @param sourcecontents 要索引的内容
     */
    public boolean batchCreateIndex(String index,String type,List<String> sourcecontents) throws Exception {
        Client client=null;
        try{
            client=esDataSource.getClient();
            BulkRequestBuilder bulkRequest=client.prepareBulk();
            for(String sourcecontent:sourcecontents){
                bulkRequest.add(client.prepareIndex(index, type).setSource(sourcecontent));
            }
            BulkResponse bulkResponse=bulkRequest.execute().actionGet();
            boolean result=bulkResponse.hasFailures();
            if(result){
                throw new Exception(bulkResponse.buildFailureMessage());
            }
            return !result;
        }finally {
            if(client!=null){
                esDataSource.releaseClient(client);
            }
        }
    }



    /**
     * 根据修改文档
     * @param index 索引名称
     * @param type  索引type
     * @param id  id
     * @param map 要索引的内容
     */
    public boolean updateIndex(String index,String type,String id,Map map) throws Exception {
        Client client=null;
        try{
            client=esDataSource.getClient();
            UpdateResponse response = client.prepareUpdate(index, type,id).setDoc(map).execute().actionGet();
            return response.isCreated();
        }finally {
            if(client!=null){
                esDataSource.releaseClient(client);
            }
        }
    }


    public boolean batchUpdateIndex(String index,String type,Map<String, Map<String, Object>> map) throws Exception {
        Client client=null;
        try{
            client=esDataSource.getClient();
            BulkRequestBuilder bulkRequest=client.prepareBulk();
            Set<String> keys=map.keySet();
            for(String key:keys){
                bulkRequest.add(client.prepareUpdate(index, type, key).setDoc(map.get(key)));
            }
            BulkResponse bulkResponse=bulkRequest.execute().actionGet();
            boolean result=bulkResponse.hasFailures();
            if(result){
                throw new Exception(bulkResponse.buildFailureMessage());
            }
            return !result;
        }finally {
            if(client!=null){
                esDataSource.releaseClient(client);
            }
        }
    }

    /**
     * 更新插入
     * @param index 索引名称
     * @param type  索引type
     * @param id  id
     * @param source 要更新的内容
     */
    public boolean updateIndexAsUpsert(String index,String type,String id,String source) throws Exception {
        Client client=null;
        try{
            client=esDataSource.getClient();
            UpdateResponse response = client.prepareUpdate(index, type, id).setDocAsUpsert(true).setUpsert(source).execute().actionGet();
            return response.isCreated();
        }finally {
            if(client!=null){
                esDataSource.releaseClient(client);
            }
        }
    }

    /**
     * 根据id删除文档
     * @param index
     * @param type
     * @param id
     */
    public boolean deleteIndex(String index, String type, String id) throws Exception {
        Client client=null;
        try{
            client=esDataSource.getClient();
            DeleteResponse response = client.prepareDelete(index, type, id)
                    .execute()
                    .actionGet();
            return response.isFound();
        }finally {
            if(client!=null){
                esDataSource.releaseClient(client);
            }
        }
    }

    /**
     * 删除多个文档
     * @param index
     * @param type
     * @param ids 多个id逗号隔开
     */
    public boolean deleteIndexs(String index, String type, String ids) throws Exception {
        Client client=null;
        try{
            client=esDataSource.getClient();
            String[] ss=ids.split(",");
            BulkRequestBuilder brb=client.prepareBulk();
            for(String id:ss){
                brb.add(client.prepareDelete(index, type, id));
            }
            BulkResponse br=brb.execute().actionGet();
            if(br.hasFailures()){
                return false;
            }
            return true;
        }finally {
            if(client!=null){
                esDataSource.releaseClient(client);
            }
        }
    }

    public boolean batchDeleteIndexs(String index,String type,List<String> ids) throws Exception {
        Client client=null;
        try{
            client=esDataSource.getClient();
            BulkRequestBuilder brb=client.prepareBulk();
            for(String id:ids){
                brb.add(client.prepareDelete(index, type, id));
            }
            BulkResponse br=brb.execute().actionGet();
            if(br.hasFailures()){
                return false;
            }
            return true;
        }finally {
            if(client!=null){
                esDataSource.releaseClient(client);
            }
        }
    }

    /**
     * 根据index前缀 统配根据给定id查询具体的index
     * @param indexPre
     * @param id
     * @return
     * @throws Exception
     */
    public String getDetailIndex(String indexPre,String type,String id) throws Exception {
        Client client=null;
        try{
            client=esDataSource.getClient();
            SearchResponse response = client.prepareSearch(indexPre)//可以同时搜索多个索引prepareSearch("index","index2")
                    .setTypes(type)//可以同时搜索多个类型
                    .setQuery(QueryBuilders.termQuery("id",id))
                    .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
                    //.setFrom(0).setSize(1).setExplain(true)
                    .execute()
                    .actionGet();
            String index=null;
            if(response.getHits().getTotalHits()>0){
                index = response.getHits().getAt(0).getIndex();
            }
            return index;
        }finally {
            if(client!=null){
                esDataSource.releaseClient(client);
            }
        }
    }

}
